package com.jzo2o.health.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.excel.EasyExcel;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.health.model.domain.ReservationSetting;
import com.jzo2o.health.model.dto.request.ReservationSettingUpsertReqDTO;
import com.jzo2o.health.model.dto.response.ReservationSettingResDTO;
import com.jzo2o.health.model.excel.ReservationImportData;
import com.jzo2o.health.service.IReservationSettingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预约设置操作
 *
 * @author itcast
 */
@Slf4j
@RestController("adminReservationSettingController")
@RequestMapping("/admin/reservation-setting")
@Api(tags = "管理端 - 预约设置相关接口")
public class ReservationSettingController {
    @Resource
    private IReservationSettingService reservationSettingService;

    @PostMapping("/upload")
    @ApiOperation("上传预约设置文件")
    public void upload(@RequestPart("file") MultipartFile file) {
        List<ReservationImportData> list;
        try {
            list = EasyExcel.read(file.getInputStream()).head(ReservationImportData.class).sheet().doReadSync();
        } catch (IOException e) {
            throw new CommonException("读取excel文件失败");
        }

        if (CollUtil.isEmpty(list)) {
            return;
        }

        List<ReservationSetting> reservationSettingList = list.stream().map(data -> {
            ReservationSetting reservationSetting = new ReservationSetting();
            reservationSetting.setOrderDate(LocalDateTimeUtil.parseDate(data.getDate(), DatePattern.NORM_DATE_PATTERN));
            reservationSetting.setNumber(data.getNumber());
            return reservationSetting;
        }).collect(Collectors.toList());
        reservationSettingService.add(reservationSettingList);
    }

    @GetMapping("/getReservationSettingByMonth")
    @ApiOperation("按月查询预约设置")
    @ApiImplicitParam(name = "date", value = "月份，格式：yyyy-MM", required = true, dataTypeClass = String.class)
    public List<ReservationSettingResDTO> getReservationSettingByMonth(@RequestParam("date") String date) {
        return reservationSettingService.getReservationSettingByMonth(date);
    }

    @PutMapping("/editNumberByDate")
    @ApiOperation("编辑预约设置")
    public void editNumberByDate(@RequestBody ReservationSettingUpsertReqDTO reservationSettingUpsertReqDTO) {
        reservationSettingService.editNumberByDate(reservationSettingUpsertReqDTO);
    }
}
